import React , { useEffect, useState }from 'react';  
import { Form, Input, Card, Row, Col,Button,Select,Spin  } from 'antd';  
import {useTranslation} from 'react-i18next'
import { template} from "@/api/modules/report";
import { listCompanyLogin} from "@/api/modules/company";
import { listCv} from "@/api/modules/cv";
import getSafetyCatefory from '../../report/step/SafetyCatefory'
import { listTest} from "@/api/modules/litermark";
import { listValue } from "@/api/modules/sccs";
import { getProductDetail,listRemark} from "@/api/modules/report";
import '../../report/step/MergedCellsTable.css'
import { forIn } from 'lodash';
import useCacheAlive from '@/hooks/useCacheAlive';

const { Option } = Select;
const BasicInfoForm = ({ onFinish ,productId,step1Value  }) => {  
  // ... 其他代码 ...  
  const { t } = useTranslation();
  const [form] = Form.useForm(); 
  const [formValue, setFormValue] = useCacheAlive({}, `table-fmScreening-formValue`) 
  const [companyList,setCompanyList] = useState([]);
  const [CVList,setCVList]  = useState([]);
  const [efficacyLists,setEfficacyLists] = useState([]);
  const [positionLists,setPositionLists] = useState([]);
  const [productlist,setProductlist] = useState([]);
  const [populationLists,setPopulationLists] = useState([]);
  const [peopleLists,setPeopleLists] = useState([]);
  const [methodLists,setMethodLists] = useState([]);
  const [zhuliuLists,setZhuliuLists] = useState([]);
  const [formulalist,setFormulalist] = useState([]);
  const [unitlist,setUnitlist] = useState([]);
  const [subjectTestList,setSubjectTestList] = useState([]);
  const [safetyCategory,setSafetyCategory] = useState([]);
  const [templateList,setTemplateList] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(()=>{
    const query = {pageNum:1,pageSize:9999,limit:9999,page:1}
    template(query).then(res=>{
        setTemplateList(res.data)
    })
    listCompanyLogin(query).then(res=>{
        setCompanyList(res.data.rows)
        if (res.data.rows && res.data.rows.length > 0) {  
            form.setFieldsValue({  
                ownerName: res.data.rows[0].companyName,  
                ownerAddress: res.data.rows[0].companyAddress,  
                appraiseCompany: res.data.rows[0].evaluationCompany,  
            });  
          }  
    })
    listCv().then(res=>{
       setCVList(res.data.rows)
       })
    listTest().then(res=>{
        setSubjectTestList(res.data.data.page)
       })
    listValue(query).then(res=>{
        setSafetyCategory(res.data.data.page);
    })
    setEfficacyLists(getSafetyCatefory("efficacy"))
    setPositionLists(getSafetyCatefory("position")) 
    setPopulationLists(getSafetyCatefory("population"))
    setPeopleLists(getSafetyCatefory("people"))
    setMethodLists(getSafetyCatefory("method"))
    setZhuliuLists(getSafetyCatefory("retentionFactor"))
    setProductlist(getSafetyCatefory("product"))
    setFormulalist(getSafetyCatefory("formula"))
    setUnitlist(getSafetyCatefory("unit"))
    if(productId !==0){
        getProductDetail(productId).then(res=>{
            let formParams=res.data.data
            if(formParams.efficacy ==null || formParams.efficacy ==undefined || formParams.efficacy ==""){
                 formParams.efficacy=""
            }else{
                if(formParams.efficacy.includes(',')){
                    formParams.efficacy = formParams.efficacy.split(',')
                }else{
                    formParams.efficacy = formParams.efficacy.split('，')
                }
               
            }
            if(formParams.form ==null || formParams.form ==undefined || formParams.form ==""){
                formParams.form=""
            }else{
                if(formParams.form.includes(',')){
                    formParams.form = formParams.form.split(',')
                }else{
                    formParams.form = formParams.form.split('，')
                }
            
            }
            if(formParams.method ==null || formParams.method ==undefined || formParams.method ==""){
                formParams.method=""
            }else{
                if(formParams.method.includes(',')){
                    formParams.method = formParams.method.split(',')
                }else{
                    formParams.method = formParams.method.split('，')
                }
               
            }
            if(formParams.population ==null || formParams.population ==undefined || formParams.population ==""){
                formParams.population=""
            }else{
                if(formParams.population.includes(',')){
                    formParams.population = formParams.population.split(',')
                }else{
                    formParams.population = formParams.population.split('，')
                }
            }
            if(formParams.people ==null || formParams.people ==undefined || formParams.people ==""){
              formParams.people=""
          }else{
              if(formParams.people.includes(',')){
                  formParams.people = formParams.people.split(',')
              }else{
                  formParams.people = formParams.people.split('，')
              }
          }
            if(formParams.position ==null || formParams.position ==undefined || formParams.position ==""){
                formParams.position=""
            }else{
                if(formParams.position.includes(',')){
                    formParams.position = formParams.position.split(',')
                }else{
                    formParams.position = formParams.position.split('，')
                }
            }
            if(formParams.classification ==null || formParams.classification ==undefined || formParams.classification ==""){
                formParams.classification=""
            }else{
                if(formParams.classification.includes(',')){
                    formParams.classification=formParams.classification.split(',')
                }else{
                    formParams.classification=formParams.classification.split('，')
                }
            }
            form.setFieldsValue(formParams)
        })
    }else{
      console.log(formValue,'formValue')
      form.setFieldsValue(formValue)
      // if(step1Value.population == undefined || step1Value.population == null || step1Value.population ==""){
      //   form.setFieldsValue({  
      //     exposureMethod:'经皮吸收',
      //     exposureRouter:'经皮途径',
      //     testDefId:3,
      //     multiFormula:"single",
      // });
      // }else{
      //   // form.setFieldsValue(step1Value)
       
      // }
     
    }
  },[productId]
)
 // 转换 templateList 为 Select 组件所需的 options 格式  
 const options = templateList.map(item => (  
    <Option key={item.id} value={item.id}>  
      {item.name}  
    </Option>  
  )); 

const CompanyNameOptions = companyList.map(item=>{
    return (  
        <Option key={item.id} value={item.companyName}>    
          {item.companyName}    
        </Option>  
      );  
})

const CompanyAddressOptions = companyList.map(item=>{
    return ( 
    <Option key={item.id} value={item.companyAddress}>  
        {item.companyAddress}  
    </Option>
    )
})

const CompanyEvaluationCompanyOptions = companyList.map(item=>{
    return ( 
    <Option key={item.id} value={item.evaluationCompany}>  
        {item.evaluationCompany}  
    </Option>
    )  
})

const CvOptions = CVList.map(item=>{
    return ( 
    <Option key={item.id} value={item.id}>  
        {item.name}  
    </Option>
    )  
})

const EfficacyOption = efficacyLists.map(item=>{
    return ( 
    <Option key={item.id} value={item.name}>  
        {item.label}  
    </Option>
    )  
})

const PositionOption = positionLists.map(item=>{
    return ( 
    <Option key={item.id} value={item.name}>  
        {item.label}  
    </Option>
    )  
})

const ProductOption = productlist.map(item=>{
    return ( 
    <Option key={item.id} value={item.name}>  
        {item.label}  
    </Option>
    )  
})

const PeopleOption = peopleLists.map(item=>{
  return ( 
  <Option key={item.id} value={item.name}>  
      {item.label}  
  </Option>
  )  
})

const PopulationOption = populationLists.map(item=>{
    return ( 
    <Option key={item.id} value={item.name}>  
        {item.label}  
    </Option>
    )  
})

const productOption = methodLists.map(item=>{
    return ( 
    <Option key={item.id} value={item.name}>  
        {item.label}  
    </Option>
    )  
})

const rententionOption = zhuliuLists.map(item=>{
    return ( 
    <Option key={item.id} value={item.name}>  
        {item.label}  
    </Option>
    )  
})

const formulaOption = formulalist.map(item=>{
    return ( 
    <Option key={item.id} value={item.value}>  
        {item.label}  
    </Option>
    )  
})

const typeOption = subjectTestList.map(item=>{
    return ( 
    <Option key={item.id} value={item.id}>  
        {item.testLevel2Cn+'/'+item.testLevel2En}  
    </Option>
    )  
})

const renderOption = (item) => {  
    return (  
      <Option key={item.id.toString()} value={item.id.toString()}>  
        {`${item.category ? `适用人群:${item.category.population}，` : ''}
         ${item.categorySccsCn ? `产品类型(CN):${item.categorySccsCn}，` : ''}  
         ${item.categorySccsEn ? `产品类型(EN):${item.categorySccsEn}，` : ''}  
         ${item.dailyAmountMg ? `日均使用量(mg/day):${item.dailyAmountMg}，` : ''}  
         ${item.retentionFactor ? `产品驻留因子:${item.retentionFactor}，` : ''}  
         ${item.exposureMgKgBwD ? `日均暴露量(mg/kg b.w. per day):${item.exposureMgKgBwD}` : ''}`}  
      </Option>  
    );  
  };  
    
  const renOptions = safetyCategory.map(renderOption);

  const FormSectionCard = ({ title, children }) => {    
    return (  
      <Card title={<div style={customTitleStyle}>{title}</div>}>  
        {children}  
      </Card>  
    );  
  };  

  const handlePopulationChange = ()=>{
    let data = form.getFieldsValue()
    if(data.method.length>0){
      if(data.method[0]=='驻留'){
        setZhuliuLists(getSafetyCatefory("retentionFactor_leaveOn"))
      }else if(data.method[0]=='淋洗'){
        setZhuliuLists(getSafetyCatefory("retentionFactor_rinse"))
      }
    }else{
      form.setFieldsValue({
        retentionFactor:""
      })
      setZhuliuLists(getSafetyCatefory("retentionFactor"))
    }
  }

  const onValuesChange=(changedValues, allValues)=>{
    console.log(changedValues.nameCn,'changedValues')
    console.log(allValues,'allValues')
    if(changedValues.nameCn==undefined && changedValues.nameEn==undefined){
      const data = allValues
      setFormValue(data)
    }
  }

  const handleChangeCategory=()=>{
    const data = form.getFieldsValue()
    let newData = []
    let adult=false
    let child=false
    let query = {pageNum:1,pageSize:9999,limit:9999,page:1,search:null}
    console.log(data.retentionFactor,'data')
    if(data.people.length>0){
      data.people.map(item=>{
        if(item=='普通人群'){ adult=true}
        if(item.indexOf('婴幼儿')>-1){ child=true}
        if(item.indexOf('儿童')>-1){ child=true}
      })
      if(adult && !child){query.search='成人'}
      if(!adult && child){query.search='儿童'}
      if(adult && child){query.search=null}
    }

    listValue(query).then(res=>{
      if(data.retentionFactor=='' || data.retentionFactor ==undefined || data.retentionFactor ==null){
        setSafetyCategory(res.data.data.page);
      }else{
        res.data.data.page.map(i=>{
          if(i.retentionFactor==data.retentionFactor){
            newData.push(i)
          }
        })
        setSafetyCategory(newData)
      }
     
    })
  }

  const customTitleStyle = {  
    fontSize: '18px', // 字体大小  
    fontWeight: 'bold', // 字体加粗  
    backgroundColor: '#f5f5f5', // 背景色变灰色 
  };  
  return (  
    <Form form={form} onFinish={onFinish} onValuesChange={onValuesChange}>    
      {/* 摘要信息、创建信息、其他信息 Card 组件 */}  
      <FormSectionCard title={t('report.basicInformation')}>  
        {/* 摘要信息的表单项 */}  
        <Row>    
          <Col span={12}>  
            <Form.Item  
              label={t('report.productChineseName')}  
              name="nameCn"  
              rules={[{ required: true, message: '请填写产品中文名！' }]}   
            >  
              <Input />  
            </Form.Item>  
          </Col>  
          <Col span={12}>  
            <Form.Item  
              label={t('report.productEnglishName')} 
              name="nameEn"  
            >  
              <Input />  
            </Form.Item>  
          </Col>  
          <Col span={12}>  
            <Form.Item  
              label={t('report.productCode')}  
              name="productCode"  
            >  
              <Input />  
            </Form.Item>  
          </Col>
        </Row>
        <Row>
          <Col span={8}>  
            <Form.Item  
              label={t('report.efficacyClaim')} 
              name="efficacy" 
            >  
              <Select mode="tags">
                {EfficacyOption}  
              </Select> 
            </Form.Item>  
          </Col> 
          <Col span={8}>  
            <Form.Item  
              label={t('report.useArea')} 
              name="position" 
            >  
              <Select mode="tags">
                {PositionOption}  
              </Select> 
            </Form.Item>  
          </Col> 
          <Col span={8}>  
            <Form.Item  
              label={t('report.productDosageForm')} 
              name="form" 
            >  
              <Select mode="tags">
                {ProductOption}  
              </Select> 
            </Form.Item>  
          </Col> 
        </Row>
        <Row>
          <Col span={8}>  
            <Form.Item  
              label={t('report.endUser')} 
              name="population" 
              rules={[{ required: true, message: '请选择使用人群！' }]}   
            >  
              <Select mode="tags">
                {PopulationOption}  
              </Select>
            </Form.Item>  
          </Col> 
          <Col span={8}>  
            <Form.Item  
              label={t('report.productType')} 
              name="method" 
              rules={[{ required: true, message: '请输入使用方法！' }]}   
            >  
             <Select mode="tags" >
                {productOption}  
              </Select>  
            </Form.Item>  
          </Col> 
          <Col span={8}>  
            <Form.Item  
              label={t('report.retentionFactor')} 
              name="retentionFactor"  
            >  
              <Select onChange={handleChangeCategory}>
                {rententionOption}  
              </Select>
            </Form.Item>  
          </Col> 
        </Row>
        <Row>
        <Col span={12}>  
            <Form.Item  
              label={t('report.usePeople')} 
              name="people" 
              rules={[{ required: true, message: '请选择适用人群！' }]}   
            >  
              <Select mode="tags" onChange={handleChangeCategory}>
                {PeopleOption}  
              </Select>
            </Form.Item>  
          </Col> 
          <Col span={12}>  
            <Form.Item  
              label={t('report.dailyExposure')} 
              name="classification" 
              rules={[{ required: true, message: '请选择暴露量！' }]}   
            >  
              <Select mode="multiple" dropdownStyle={{ minWidth: '900px' }} >
                {renOptions}  
              </Select>  
            </Form.Item>  
          </Col> 
        </Row>
      </FormSectionCard>  
      <Row justify="center" align="middle">  
        <Col>  
        <Button type="primary" htmlType="submit" style={{ marginTop: '20px' }}>  
            {t('report.Next')}  
        </Button>  
        </Col>  
    </Row>   
    </Form>  
  );  
};  
  
export default BasicInfoForm;